package com.park.interceptor;

import com.park.common.util.StrUtil;
import com.park.controller.BaseController;
import com.park.wx.WeiXinConnector;
import org.apache.log4j.Logger;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AuthorizationHandlerInterceptor extends BaseController implements HandlerInterceptor {

    private static Logger logger = Logger.getLogger(AuthorizationHandlerInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try{
            if (!(handler instanceof HandlerMethod)) {
                return true;
            }

            logger.info("URL：" + request.getRequestURL());

            //Object shareId = request.getParameter(IPlatformConstant.SHARE_ID); //之前加密，到OAuth2解密(之前暂不加密，方便测试，下面直接加密)
            if(getUserInfo2() == null) { //未登录
                String url = WeiXinConnector.oauth2_url.replace("APPID", WeiXinConnector.APP_ID).replace("REDIRECT_URI", WeiXinConnector.DOMIAN + request.getContextPath() + "/oAuth2"); //wxAuthorizationRedirectUri
                //分享人openId已追加在最后
                String param = request.getRequestURL() + StrUtil.getQueryString(request);
                //url = url.replace("STATE", URLEncoder.encode(param, "UTF-8"));//URLEncoder.encode(SymmetricEncoder.encrypt(param), "UTF-8"));
                url = url.replace("STATE", param);
                logger.info("未登录，去授权！" + url);
                //logger.info("长度：" + URLEncoder.encode(param, "UTF-8").length());
                response.sendRedirect(url);
                return false;
            }
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
        logger.info(getUserInfo2().getOperatorName()+"：已登陆，直接访问！");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        request.setAttribute("static_resource_version", System.currentTimeMillis());
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
